import store from '@/store/index'
import { ObjectOwn } from '@/utils/tools'
import { proxy } from '../../url.config'
// import { proxy } from '../../vite.config'

// const url = process.env.VITE_API_URL

const setProxy = (u) => {
  let n = ''
  proxy.find((v) => {
    const i = v.indexOf(':')
    const l = v.substring(0, i).replace('/', '\\/')
    const r = v.substring(i + 1)
    const reg = new RegExp(l)
    if (reg.test(u)) {
      n = u.replace(reg, (_, $1) => {
        return r
      })
      return true
    } else {
      return false
    }
  })
  console.log(n)
  return n
}

interface options {
  url: string
  data?: object
}

export function beOver() {
  // 重新登录
  // uni.removeStorageSync('token')
  store.commit('setToken')
  uni.removeStorageSync('userInfo')
  store.dispatch('im/IM_DISCONNECT')

  store.dispatch('setUserInfo', {
    success: () => {
      const pages = getCurrentPages() // 获取当前打开过的页面栈
      const url = pages[pages.length - 1].route // 获取当前页面的路径

      const tabs = []

      if (tabs.includes(url)) {
        uni.switchTab({
          url: '/' + url
        })
      } else {
        uni.redirectTo({
          url: '/' + url
        })
      }
    }
  })
}

function get(options: options): Promise<{} | undefined> | void {
  return new Promise<{} | undefined>((resolve, reject) => {
    // const token =
    const token = store.state.token
    uni.request({
      url: setProxy(options.url),
      method: 'GET',
      data: options.data,
      header: {
        'Content-Type': 'application/json',
        Token: token
      },
      dataType: 'json',
      success: (respoones: any) => {
        if (respoones.statusCode == '200') {
          if (respoones.data.code != 0) {
            if (respoones.data.code === 4011) {
              uni.hideLoading()
              uni.showModal({
                title: '您当前的登录信息已过期，点击确定重新登录',
                icon: 'none',
                showCancel: false,
                success: (res) => {
                  beOver()
                }
              })
              reject({
                code: 401,
                msg: 'token过期'
              })
            } else if (ObjectOwn(options, 'catchError') && options.catchError) {
              reject(respoones.data)
            } else {
              uni.showToast({
                icon: 'none',
                title: respoones.data.message,
                duration: 2000
              })
              reject(respoones.data)
            }
          }
          resolve(respoones.data)
        } else if (respoones.statusCode == 401) {
          uni.showModal({
            title: '您当前的登录信息已过期，点击确定重新登录',
            icon: 'none',
            showCancel: false,
            success: (res) => {
              beOver()
            }
          })
          reject({
            code: 401,
            msg: 'token过期'
          })
        } else {
          reject({
            code: 500,
            msg: '服务器异常'
          })
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '请求失败',
          icon: 'none'
        })
        reject({
          code: 404,
          msg: '请求失败'
        })
      }
    })
  })
}

function post(options: options): Promise<{} | undefined> | void {
  return new Promise<{} | undefined>((resolve, reject) => {
    // const token = uni.getStorageSync('token')
    const token = store.state.token
    uni.request({
      url: setProxy(options.url),
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        Token: token
      },
      timeout: 30000,
      data: options.data,
      dataType: 'json',
      success: (respones: any) => {
        if (respones.statusCode == 200) {
          if (respones.data.code !== 0) {
            if (respones.data.code === 4011) {
              uni.hideLoading()
              uni.showModal({
                title: '您当前的登录信息已过期，点击确定重新登录',
                icon: 'none',
                showCancel: false,
                success: (res) => {
                  beOver()
                }
              })
              reject({
                code: 401,
                msg: 'token过期'
              })
            } else if (ObjectOwn(options, 'catchError') && options.catchError) {
              reject(respoones.data)
            } else {
              uni.showToast({
                icon: 'none',
                title: respones.data.message,
                duration: 2000
              })
              reject(respones.data)
            }
          }
          resolve(respones.data)
        } else if (respones.statusCode == 401) {
          uni.showModal({
            title: '您当前的登录信息已过期，点击确定重新登录',
            icon: 'none',
            showCancel: false,
            success: (res) => {
              beOver()
            }
          })
          reject({
            code: 401,
            msg: 'token过期'
          })
        } else {
          reject({
            code: 500,
            msg: '服务器异常'
          })
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '请求失败',
          icon: 'error'
        })
        reject({
          code: 404,
          msg: '请求失败'
        })
        // throw new Error('请求失败');
      },
      complete: () => {}
    })
  })
}

interface uploadOptions {
  url: string
  file: any
  name?: string
}

function upload(options: uploadOptions): Promise<{} | undefined> | void {
  return new Promise<{} | undefined>((resolve, reject) => {
    uni.showLoading({
      mask: true,
      title: '上传中...'
    })
    const token = store.state.token
    uni.uploadFile({
      url: setProxy(options.url),
      header: {
        Token: token
      },
      filePath: options.file,
      fileType: 'image',
      name: options.name || 'file',
      formData: options.formData || {},
      success: (respones: any) => {
        const res = JSON.parse(respones.data)
        if (respones.statusCode === 200) {
          if (res.code === 0) {
            resolve(res)
          } else {
            reject(res)
          }
        } else {
          reject({
            code: 500,
            msg: '上传失败'
          })
        }
      },
      fail: (err) => {
        reject({
          code: 500,
          msg: '上传失败'
        })
        throw new Error('上传失败')
      },
      complete: () => {
        uni.hideLoading()
      }
    })
  })
}

export default {
  get: get,
  post: post,
  upload: upload
}
